package com.lcredu.sqlSeesion;

import com.lcredu.config.Function;
import com.lcredu.config.MapperBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author 黎长容
 * @date 2025-07-29 11:42
 * 动态生成一个mapper对象,调用Executor方法
 */
public class LcrMapperProxy implements InvocationHandler {
    //如果我要在这里进行sql调用,那么前面封装好的sqlSession是必要的
    private LcrSqlSession sqlSession;
    //mapper文件
    private String mapperFile;
    //读取xml文件
    private LcrConfiguration lcrConfiguration;

    public LcrMapperProxy(LcrSqlSession sqlSession, LcrConfiguration configuration, Class clazz) {
        this.lcrConfiguration = configuration;
        this.sqlSession = sqlSession;
        this.mapperFile = clazz.getSimpleName() + ".xml";
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MapperBean mapperBean = lcrConfiguration.readMapper(this.mapperFile);
        //如果接口名和存入的接口名不一致,则直接返回一个null
        if (!method.getDeclaringClass().getName().equals(mapperBean.getInterfaceName())) {
            return null;
        }

        List<Function> functions = mapperBean.getFunctions();
        //判断方法名
        if (!(functions.size() == 0 || functions == null)){
            for (Function function : functions) {
                if (method.getName().equals(function.getMethodName())){
                    //如果方法名和接口名一致,则继续调用
                    //简化了
                    return sqlSession.selectOne(function.getSql(),args[0]);
                }
            }
        }
        
        return null;

    }
}
